package edu.wong.pro.serviceImpl;

import java.util.List;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import edu.wong.pro.dao.CommentDAO;
import edu.wong.pro.iservice.IComment;
import edu.wong.pro.model.Comment;
import edu.wong.pro.other.OtherService;

public class CommentService implements IComment{

	//发表评论
	@Override
	public void relComment(String newsID, String comContent) {
		// TODO Auto-generated method stub
		int newsId = Integer.parseInt(newsID.trim());
		HttpSession httpSession = ServletActionContext.getRequest().getSession();
		String memId = httpSession.getAttribute("memberID").toString();
		String date = OtherService.getCurrentTime();
		Comment comment = new Comment(newsId, memId, date, comContent, getMaxFloor(newsId), 0);
		CommentDAO dao = new CommentDAO();
		Session session = dao.getSession();
		Transaction transaction = session.beginTransaction();
		dao.save(comment);
		transaction.commit();
		session.close();	
	}

	//获取当前帖子的所有评论
	@Override
	public JSONArray getAllComment(String newsId) {
		// TODO Auto-generated method stub
		CommentDAO dao = new CommentDAO();	
		return JSONArray.fromObject(dao.findByProperty("newsId", Integer.parseInt(newsId.trim())));
	}
	
	//获取当前评论的楼层
	private int getMaxFloor(int newsId){
		Configuration configuration = new Configuration().configure();
		SessionFactory factory = configuration.buildSessionFactory();
		Session session = factory.openSession();
	    Query query = session.createQuery("select max(floor) as maxfloor from Comment where newsId="+newsId);
		List<Integer>  list= query.list();
		session.close();
		factory.close();
		if(list.get(0)!=null){
			return list.get(0)+1;
		}
		return 1;
	}

}
